
/** WebSocket */
export default function useSocket({ payload, onSocketMessage }: { payload: Record<string, any>, onSocketMessage?: (data: Record<string, any>) => void }) {
	/** 用户 */
	const { user } = uni.$store();
	
	/** 创建一个 WebSocket 连接 */
	uni.connectSocket({
		url: `wss://www.crazytraining.cn/hunyuan?token=${user.token}`
		// url: `ws://test.deepinfo.cn:9794/hunyuan?token=${user.token}`
	});
	
	/** 监听WebSocket连接打开事件 */
	uni.onSocketOpen(() => {
		uni.sendSocketMessage({
			data: JSON.stringify({ 
				payload,
				type: 'chat',
			})
		});
	});
	
	
	/** 监听WebSocket接受到服务器的消息事件  */
	let text = '';
	uni.onSocketMessage(async result => {
		const id = Math.random().toString().slice(2, 8);
		const data = JSON.parse(result.data);
		if (data.message === 'success') {
			text += data.data;
			onSocketMessage({
				id,
				text: data.data?.trim?.('\n')?.trim?.('\r\n')?.replace?.('.",', '.')?.replace?.(' "', '')?.replace?.('"', '')?.replace?.('\\', ''),
			});
		};
		
		if (data.data?.id) {
			onSocketMessage({
				id,
				articleId: data.data?.id
			});
			
			uni.closeSocket({
				fail: () => {}
			});
		};
		
		if (data.error) {
			onSocketMessage({
				id,
				error: data.error
			});
			
			uni.closeSocket({
				fail: () => {}
			});
		};
	});
};